package com.fuyun.rpc.common.security;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 认证器工厂类
 */
public class AuthenticatorFactory {
	private static final Map<String, Authenticator> INSTANCE_CACHE = new ConcurrentHashMap<>();

	/**
	 * 获取指定类名的 Authenticator 单例实例
	 *
	 * @param className 实现类全限定名
	 * @return Authenticator 单例对象
	 */
	public static Authenticator getInstance(String className) {
		return INSTANCE_CACHE.computeIfAbsent(className, key -> {
			try {
				Class<?> clazz = Class.forName(key);
				if (!Authenticator.class.isAssignableFrom(clazz)) {
					throw new IllegalArgumentException("Class " + key + " 未实现 Authenticator 接口");
				}
				return (Authenticator)clazz.getDeclaredConstructor()
					.newInstance();
			} catch (ClassNotFoundException e) {
				throw new RuntimeException("找不到类: " + key, e);
			} catch (InstantiationException e) {
				throw new RuntimeException("无法实例化类: " + key + "（可能是抽象类）", e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException("无权限访问构造函数: " + key, e);
			} catch (NoSuchMethodException e) {
				throw new RuntimeException("类 " + key + " 缺少无参构造函数", e);
			} catch (InvocationTargetException e) {
				throw new RuntimeException("构造函数执行失败: " + key, e.getTargetException());
			}
		});
	}
}